package com.sphd.emanu.activity.goodsfrom;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sphd.emanu.R;
import com.sphd.emanu.activity.addgoodfrom.AddGoodFromActivity;
import com.sphd.emanu.adapter.GoodsfromAdapter;
import com.sphd.emanu.config.Constant;
import com.sphd.emanu.mvp.MVPBaseActivity;
import com.sphd.emanu.permission.Moudle;
import com.sphd.emanu.pojo.goods.Commodity;
import com.sphd.emanu.pojo.goods.Composition;
import com.sphd.emanu.pojo.login.User;
import com.sphd.emanu.utils.PermissionConfig;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * 商品的构成
 *
 * @Author Hu
 * @Time 2017/5/3 -- 17:01.
 * @Email 87683202@qq.com
 */
public class GoodsfromActivity extends MVPBaseActivity<GoodsfromContract.View, GoodsfromPresenter> implements GoodsfromContract.View, View.OnClickListener {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.my_recycler)
    RecyclerView myRecycler;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    View heradView;
    GoodsfromAdapter goodsfromAdapter;
    @BindView(R.id.edit_list)
    TextView editList;
    TextView addFood, goodName, goodSrc, goodCom, title, first, second, cancle;
    Intent intent;
    Bundle bundle;
    Commodity commodity;
    View viewDialog;
    AlertDialog alertDialog;
    int dialogType;
    User user;
    List<Moudle> moudles;
    boolean isCanDo = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goodsfrom);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> finish());
        first.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialogType == 0) {
                    goodSrc.setText("外购");
                    goodCom.setText("购买");
                    showWarningDialog("1", "1");
                } else {
                    alertDialog.dismiss();
                    goodCom.setText("制造");
                    showWarningDialog("2", "2");
                }
            }
        });
        second.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialogType == 0) {
                    goodSrc.setText("自制");
                    goodCom.setEnabled(true);
                    alertDialog.dismiss();
                    title.setText("请选择商品构成");
                    first.setText("制造");
                    second.setText("装配");
                    dialogType = 1;
                    alertDialog.show();
                } else {
                    goodCom.setText("装配");
                    showWarningDialog("2", "3");
                }

            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });


        goodSrc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                title.setText("请选择商品来源");
                first.setText("外购");
                second.setText("自制");
                dialogType = 0;
                goodCom.setEnabled(true);
                alertDialog.show();
            }
        });
        goodCom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                title.setText("请选择商品构成");
                first.setText("制造");
                second.setText("装配");
                dialogType = 1;
                alertDialog.show();
            }
        });

        myRecycler.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

                final Composition composition = (Composition) adapter.getItem(position);
                if (null != composition.getProduct()) {
                    Commodity commodity = new Commodity();
                    commodity.setId(composition.getProduct());
                    commodity.setCategoryName(composition.getCategoryName());
                    bundle.putSerializable(Constant.COMMODITY, commodity);
                    intent.setClass(context, GoodsfromActivity.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }


            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                super.onItemChildClick(adapter, view, position);
                final Composition composition = (Composition) adapter.getItem(position);
                switch (view.getId()) {
                    case R.id.item_edit:
                        bundle.putSerializable(Constant.COMMODITY, commodity);
                        bundle.putSerializable(Constant.COMPOSOTION, composition);
                        bundle.putInt(Constant.FLAG, 1);
                        intent.setClass(context, AddGoodFromActivity.class);
                        intent.putExtras(bundle);
                        startActivityForResult(intent, Constant.REQUEST_CODE);
                        break;
                    case R.id.item_del:
                        new SweetAlertDialog(context, SweetAlertDialog.NORMAL_TYPE).setTitleText("删除").setContentText("确定要删除" +
                                composition.getName() + "吗?").setConfirmText("确定").setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                mPresenter.deleteComposition(composition.getId(), sweetAlertDialog, position);
                            }
                        }).setCancelText("取消").setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismiss();
                            }
                        }).show();
                        break;

                }
            }
        });
    }

    private void showWarningDialog(final String source, final String composition) {
        new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE).setTitleText("确定修改？").setConfirmText("确定").setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                mPresenter.updateCommoditySrcCome(commodity.getId(), source, composition, commodity.getCategory(),
                        user.getOid(), sweetAlertDialog);
            }
        }).setCancelText("取消").setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
            }
        }).show();
    }

    private void initView() {
        setTitleBar(toolbar, "商品构成");
        setRefresh(mySwf);
        setRecy(myRecycler);
        intent = getIntent();
        bundle = intent.getExtras();
        commodity = (Commodity) bundle.getSerializable(Constant.COMMODITY);
        user = (User) bundle.getSerializable(Constant.USER_ENTITY);
        moudles = (List<Moudle>) bundle.getSerializable(Constant.PERMISSION_LIST);
        isCanDo = isCanDo(moudles, PermissionConfig.MENU_FOOD_1);
        if (isCanDo) {
            editList.setVisibility(View.VISIBLE);
        }
        initDialog();
        initAdapter();
        initHeardView();
        addData();
    }

    /**
     * 上传对话框
     */
    private void initDialog() {
        viewDialog = View.inflate(context, R.layout.dialog_choose, null);
        title = (TextView) viewDialog.findViewById(R.id.title);
        first = (TextView) viewDialog.findViewById(R.id.first);
        second = (TextView) viewDialog.findViewById(R.id.second);
        cancle = (TextView) viewDialog.findViewById(R.id.cancle);
        alertDialog = getDialogBuilder(viewDialog, R.style.AlertDialog);

    }

    private void addData() {
        showProgressDialog();
        mPresenter.getFromList(commodity.getId());
    }

    private void initAdapter() {
        goodsfromAdapter = new GoodsfromAdapter(R.layout.item_goods_from, new ArrayList<Composition>());
        goodsfromAdapter.setEmptyView(emptyView);
        myRecycler.setAdapter(goodsfromAdapter);
    }

    /**
     * recyclerview头部
     */
    private void initHeardView() {
        heradView = View.inflate(context, R.layout.heardview_goods_from, null);
        goodName = (TextView) heradView.findViewById(R.id.good_name);
        goodSrc = (TextView) heradView.findViewById(R.id.item_source);
        goodCom = (TextView) heradView.findViewById(R.id.item_composition);
        addFood = (TextView) heradView.findViewById(R.id.add_good);
        goodsfromAdapter.addHeaderView(heradView);
        addFood.setOnClickListener(this);

    }

    @Override
    public void setEntity(Commodity commodity) {
        dissProgressDialog();
        this.commodity = commodity;
        goodName.setText(commodity.getName());
        goodSrc.setText(commodity.getSource().equals("1") ? "外购" : "自制");
        goodCom.setText(commodity.getComposition().equals("1") ? "购买" : commodity.getComposition().equals("2") ? "制造" : "装配");

        goodsfromAdapter.setNewData(commodity.getCompositions());
    }

    @Override
    public void setDelRes(int res, SweetAlertDialog sweetAlertDialog, int position) {
        dissProgressDialog();
        if (res == 1) {
            toast("删除成功");
            sweetAlertDialog.dismiss();
            goodsfromAdapter.remove(position);
        } else {
            toast("删除失败，请重试。");
        }
    }

    @OnClick(R.id.edit_list)
    public void onViewClicked() {
        // TODO: 2017/6/14 隐藏编辑按钮 显示新增的按钮 对list显示“编辑”和“删除”功能按键 刷新list
        editList.setVisibility(View.GONE);
        addFood.setVisibility(View.VISIBLE);
        goodSrc.setEnabled(true);
        if (commodity.getComposition().equals("1")) {
            goodCom.setEnabled(false);
        }
        goodsfromAdapter.setEdit(true);
        goodsfromAdapter.notifyDataSetChanged();

    }

    @Override
    public void setUpRes(int res, SweetAlertDialog sweetAlertDialog) {
        if (res == 1) {
            toast("修改成功");
            sweetAlertDialog.dismiss();
            alertDialog.dismiss();

        } else {
            toast("修改失败，请重试。");

        }
    }

    @Override
    public void onClick(View v) {
        bundle.putSerializable(Constant.COMMODITY, commodity);
        bundle.putSerializable(Constant.COMPOSOTION, null);
        bundle.putInt(Constant.FLAG, 0);
        intent.setClass(context, AddGoodFromActivity.class);
        intent.putExtras(bundle);
        startActivityForResult(intent, Constant.REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUEST_CODE) {
            addData();
        }
    }
}
